<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Http\Requests\UserRequest;
use App\Models\Post;
use App\Models\User;
use Faker\Generator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{


    public function __construct()
    {
        $this->middleware('auth',[
            'except'=>['index','show','create','store','confirmEmail']
        ]);
    }

    public function index(User $user) {
        $new_user = $user->getNewUser();
        $users = User::query()->paginate(20);
        $active_users = $new_user->get('active_users');
        $register_users = $new_user->get('register_users');
        return view('users.index',compact('users','active_users','register_users'));
    }

    public function show(User $user) {
        $posts = Post::query()->where('user_id',$user->id)->orderByDesc('updated_at')->paginate(10);
        return view('users.show',compact('user','posts'));
    }

    public function edit(User $user) {
        $this->authorize('update',$user);
        return view('users.edit',compact('user'));
    }

    public function update(User $user,UserRequest $request,ImageUploadHandler $handler) {

        $this->authorize('update',$user);
        $image = $handler->save($request->image,'avatar','avatar');
        $data = $request->all(['name','is_admin','email','introduction']);
        $data['image'] = $image['path'] ?:'';
        if ($request->password) {
            $data['password'] = Hash::make($request->password);
        }
        $user->update($data);
        session()->flash('success','个人资料更新成功!');
        return redirect()->route('users.show',$user);
    }

    public function destroy(User $user) {
        $this->authorize('destroy',$user);
        $user->delete();
        session()->flash('success','成功删除用户!');
        return redirect()->route('users.index');
    }

    public function confirmEmail($token) {
        $user = User::query()->where('activation_token',$token)->firstOrFail();
        $user->activation_token = null;
        $user->activated = true;
        $user->save();
        Auth::login($user);
        session()->flash('success','账号激活成功!');
        return redirect()->route('users.show',compact('user'));
    }
}
